<template>
  <div>
    <el-popover
      ref="dcPopover"
      placement="top"
      :title="topTitle"
      width="418"
      offset="0"
      :autoCreate="false"
      trigger="manual"
      :popper-options="{ boundariesElement: 'viewport', removeOnDestroy: true }"
      v-model="visible"
      @hide="hide">
      <div style="position: absolute;right: 10px;top: 10px;cursor:pointer" @click="visible = false">
        <d2-icon name="close" style="margin-right: 3px;"/>
      </div>
      <div style="text-align: center">
        <div class="qrcode">
          <span v-if="!qrcode">
            <div style="width: 215px;height: 215px;">
              <div slot="error" class="image-slot">
                二维码已失效
              </div>
            </div>
          </span>
          <span ref="qrCodeUrl"/>
        </div>
        <div v-if="state!==2">
          {{ tipsTitle }}
        </div>
        <div v-else>
          <d2-icon name="check-circle" style="margin-right: 3px;color:#83C257;"/>
          已扫码
        </div>
        <div style="cursor:pointer" @click="initCode">
          <d2-icon name="refresh" style="margin-right: 3px;"/>
          刷新
        </div>
      </div>
      <el-button slot="reference" class="dingtalk-button" type="success" size="small" circle @click="feishuLoginClick">
        <!-- style="width: 100%;"> -->
        <img src="../../icon/dingtalk-icon.png" style="vertical-align: bottom; height: 14px;"/>
      </el-button>
    </el-popover>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import util from '@/libs/util'
import * as api from './api'
// import { urlPrefix } from '@/views/system/whiteList/api'

export default {
  name: "dingtalkLogin",
  props: {
    loginType: {
      require: false
    },
    topTitle: {
      require: false,
      default: '飞书登录'
    },
    tipsTitle: {
      require: false,
      default: '请使用飞书扫一扫进行扫码登录'
    },
    buttonTitle: {
      require: false,
      default: '飞书扫码登录'
    },
  },
  watch: {
    state: {
      handler() {
        if (this.state === 0) {
          this.qrcode = ""
          this.$refs.qrCodeUrl.innerHTML = ""
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      visible: false,
      qrcode: '',
      QrCodeVal: '',
      loginUid: '',
      state: 1, // 0 无效，1 未扫，2 已扫，3 扫码完成,并返回token
      setIntervalItem: '',
      setIntervalCount: 0,
      setIntervalTime: 3000
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    initCode() {// 初始化二维码
      this.state = 1
      let baseURL = util.baseURL()
      if (baseURL.startsWith('/')) {
        baseURL = location.protocol + '//' + location.hostname + (location.port ? ':' : '') + location.port + baseURL
      }
      api.ScanLoginUrl({login_type: this.loginType}).then(res => {
        this.loginUid = res.data.login_uid
        this.creatQrCode(res.data.url)
        // res.data.params.redirect_uri = encodeURIComponent(baseURL + api.urlPrefix + 'confirm/confirm_login/')
        // res.data.params.redirect_uri = encodeURIComponent('http://127.0.0.1' + api.urlPrefix + 'confirm/confirm_login/')
        // let ar = []
        // for (var i in res.data.params) {
        // ar.push(i + '=' + res.data.params[i])
        // }
        // let url = res.data.url + '?' + ar.join('&') + '#' + res.data.anchor
        // this.creatQrCode(url)
        // console.log(res.data.params)
      })
    },
    creatQrCode(text) {
      console.log(111111, text)
      if (this.$refs.qrCodeUrl) {
        this.$refs.qrCodeUrl.innerHTML = ""
      }
      this.QrCodeVal = text
      this.qrcode = new QRCode(this.$refs.qrCodeUrl, {
        text: text, // 需要转换为二维码的内容
        width: 215,
        height: 215,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
      // 清除定时器并重置
      clearInterval(this.setIntervalItem)
      this.setIntervalCount = 0
      this.startInterval()
    },
    // 校验扫码状态
    verifyWhetherScan() {
      // 如果2分钟后将无效二维码
      if (this.setIntervalCount * this.setIntervalTime > 120000) {
        this.state = 0
        clearInterval(this.setIntervalItem)
        return
      }
      api.VerifyWhetherScan({login_uid: this.loginUid}).then(async res => {
        this.state = res.data.state
        if (res.data.state === 3 && res.data.token) {
          // util.cookies.set('uuid', res.userId)
          util.cookies.set('token', res.data.token)
          util.cookies.set('refresh', res.data.token)
          // 获取对应token，并进行登录
          clearInterval(this.setIntervalItem)
          this.setIntervalCount = 0
          await this.$store.dispatch('d2admin/account/load')
          // this.$router.replace(this.$route.query.redirect || '/')
          this.$router.replace('/')
        }
      })
      this.setIntervalCount += 1
    },
    startInterval() {
      this.setIntervalItem = setInterval(() => {
        this.verifyWhetherScan()
      }, this.setIntervalTime)
    },
    feishuLoginClick() {
      this.initCode()
      this.visible = true
    },
    hide() {
      if (this.setIntervalItem) {
        clearInterval(this.setIntervalItem); //关闭
      }
    }
  }

}
</script>

<style scoped lang="scss">
.dingtalk-button {
  background-color: rgba(0, 128, 255, 1);
  border-color: rgba(0, 128, 255, 1);
}

.dingtalk-button:hover {
  background-color: rgba(0, 128, 255, 0.8);
}

.qrcode {
  display: inline-block;
  margin: 30px auto;

  img {
    width: 132px;
    height: 132px;
    background-color: #f5f7fa; //设置白色背景色
    padding: 6px; // 利用padding的特性，挤出白边
    box-sizing: border-box;
  }
}

::v-deep .image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 18px;
}
</style>
